import { NextRequest, NextResponse } from 'next/server';
import { authMiddleware, TokenPayload } from '@/utils/auth';
import UserModel from '@/models/user';
import bcrypt from 'bcryptjs';

export async function POST(request: NextRequest) {
  try {
    // 验证用户身份
    const authResult = await authMiddleware(request);
    if (authResult instanceof NextResponse) {
      return authResult; // 返回错误响应
    }

    const decoded = authResult as TokenPayload;
    const userId = decoded.id;

    // 获取用户信息
    const user = await UserModel.findById(userId);
    if (!user) {
      return NextResponse.json(
        { error: '用户不存在' },
        { status: 404 }
      );
    }

    // 解析请求体
    const body = await request.json();
    const { positionId, password } = body;

    // 验证必填字段
    if (!positionId) {
      return NextResponse.json(
        { error: '缺少职位ID' },
        { status: 400 }
      );
    }

    if (!password) {
      return NextResponse.json(
        { error: '请输入密码以验证身份' },
        { status: 400 }
      );
    }

    // 验证密码是否正确
    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (!isPasswordValid) {
      return NextResponse.json(
        { error: '密码错误，请重新输入' },
        { status: 401 }
      );
    }

    // 获取企业信息
    const [companies] = await UserModel.query<any[]>(
      `SELECT * FROM companies WHERE admin_user_id = ?`,
      [userId]
    );

    const company = Array.isArray(companies) && companies.length > 0 ? companies[0] : null;

    if (!company) {
      return NextResponse.json(
        { error: '未找到您管理的企业信息' },
        { status: 404 }
      );
    }

    // 首先尝试从 job_positions 表中查找职位
    // 匹配创建者ID或公司ID
    const [positions] = await UserModel.query<any[]>(
      `SELECT jp.* FROM job_positions jp
       JOIN companies c ON jp.company_id = c.id
       WHERE jp.id = ? AND (jp.created_by = ? OR (c.admin_user_id = ? AND jp.company_id = c.id))`,
      [positionId, userId, userId]
    );

    // 如果在 job_positions 表中找到了职位，则直接删除
    if (Array.isArray(positions) && positions.length > 0) {
      // 删除职位前，获取相关简历数量
      const [resumeCount] = await UserModel.query<any[]>(
        `SELECT COUNT(*) as count FROM resume_submissions WHERE position_id = ?`,
        [positionId]
      );

      // 删除职位 - 只需要匹配ID，因为我们已经验证了权限
      await UserModel.query(
        `DELETE FROM job_positions WHERE id = ?`,
        [positionId]
      );

      console.log(`删除职位 ID ${positionId} 成功，相关简历数量: ${resumeCount[0]?.count || 0}`);

      return NextResponse.json(
        { message: '职位已成功删除' },
        { status: 200 }
      );
    }

    // 如果在 job_positions 表中没有找到，则尝试从 resume_submissions 表中查找
    const [resumePositions] = await UserModel.query<any[]>(
      `SELECT DISTINCT position_id, position_name
       FROM resume_submissions
       WHERE position_id = ? AND company_id = ?`,
      [positionId, company.id]
    );

    if (!Array.isArray(resumePositions) || resumePositions.length === 0) {
      return NextResponse.json(
        { error: '职位不存在或您无权删除此职位' },
        { status: 403 }
      );
    }

    // 删除与该职位相关的所有简历提交记录
    await UserModel.query(
      `DELETE FROM resume_submissions WHERE position_id = ? AND company_id = ?`,
      [positionId, company.id]
    );

    return NextResponse.json(
      { message: '职位已成功删除' },
      { status: 200 }
    );

  } catch (error) {
    console.error('删除职位错误:', error);
    return NextResponse.json(
      { error: '服务器错误，请稍后再试' },
      { status: 500 }
    );
  }
}
